import React from 'react';
import { PageLoading } from '@ant-design/pro-layout';
import { Redirect, connect } from 'umi';
import { stringify } from 'querystring';

class SecurityLayout extends React.Component {
  state = {
    isReady: false,
  };
  componentWillMount(){
    const { dispatch } = this.props;
    if(location.search !== ''){
      const isCode = location.search.split('=')[0]
      const param = location.search.split('=')[1]
      if(isCode == '?code'){
        dispatch({
          type:'login/codeLogin',
          payload:{code:param}
        })
      }
    }
  }
  componentDidMount() {
    const { dispatch } = this.props;
    this.setState({
      isReady: true,
    });

    if (dispatch) {
      dispatch({
        type: 'user/fetchCurrent',
      });
    }
  }

  render() {
    const { isReady } = this.state;
    const { dispatch, children, loading, currentUser } = this.props; // You can replace it to your authentication rule (such as check token exists)
    // 你可以把它替换成你自己的登录认证规则（比如判断 token 是否存在）
    currentUser.region && dispatch({
      type: 'houseCommon/fetchRegionGeo',
      payload: {adcode: currentUser.region_code}
    });
    const isLogin = !!currentUser;
    const queryString = stringify({
      redirect: window.location.href,
    });
    

    if ((!isLogin && loading) || !isReady) {
      return <PageLoading />;
    }

    if (!isLogin && window.location.pathname !== '/user/login') {
      return <Redirect to={`/user/login?${queryString}`} />;
    }

    return children;
  }
}

export default connect(({ user, loading ,login}) => ({
  currentUser: user.currentUser,
  loading: loading.models.user,
  login
}))(SecurityLayout);
